package com.ywgt.system.auth;

import com.ywgt.system.pojo.Menu;
import com.ywgt.system.pojo.Role;
import com.ywgt.system.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 根据请求的url获取可以访问的列表
 */
@Component
public class CustomerFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private MenuService menuService;
    AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取请求的url
        FilterInvocation filterInvocation=(FilterInvocation)o;
        String requestUrl = filterInvocation.getRequestUrl();
        if (requestUrl.contains("?")){
            int i = requestUrl.indexOf("?");
            requestUrl= requestUrl.substring(0,i);
        }
        //根据角色获取全部菜单
        List<Menu> menus = menuService.getMenuByRole();
        //循环判断请求的url与menu中的是否匹配
            for (Menu menu : menus) {
                if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                    String[] strings = menu.getRoles().stream().map(Role::getRoleName).toArray(String[]::new);
                    return SecurityConfig.createList(strings);
                }
            }

        //默认登录
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
